package com.king.juc.terminationmode;

import lombok.extern.slf4j.Slf4j;

/**
 * 两阶段终止模式
 *      volatile 改进两阶段终止模式
 *          注: volatile仅对其他线程可见, 不是原子性操作
 * @author king
 * @date 2020/11/27 22:06
 */
@Slf4j(topic = "c.TwoStageTerminationMode")
public class TwoStageTerminationMode {
    private Thread monitor;
    /**
     * 标记停止
     */
    private volatile boolean stop;

    /**
     * 启动监控线程
     */
    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                if (stop) {
                    log.debug("后续收尾逻辑.....");
                    break;
                }

                try {
                    // 情况1
                    Thread.sleep(1000);
                    // 情况2
                    log.debug("执行监控记录.....");
                } catch (InterruptedException e) {
                    // sleep出现异常后, 会清除打断标记
                    e.printStackTrace();
                    // 设置打断标记
                    current.interrupt();
                }
            }
        });

        monitor.start();
    }

    /**
     * 停止监控线程
     */
    public void stop() {
        stop = true;
        monitor.interrupt();
    }

    public static void main(String[] args) throws InterruptedException {
        TwoStageTerminationMode tpt = new TwoStageTerminationMode();
        tpt.start();

        Thread.sleep(3500);
        log.debug("停止监控......");
        tpt.stop();
    }
}
